package com.stox.client.ui.javafx.chartingy.persistence.chart.widget;

import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import javafx.collections.ListChangeListener;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;

import com.stox.client.api.core.Client;
import com.stox.client.ui.javafx.chartingy.persistence.chart.dto.ChartingViewDTO;
import com.stox.client.ui.javafx.chartingy.persistence.chart.model.OChartGroup;
import com.stox.client.ui.javafx.chartingy.view.ChartingView;
import com.stox.shared.charting.model.SavedChart;
import com.stox.shared.core.i18n.MessageSource;
import com.stox.shared.core.model.Scrip;

public class SaveAsChartMenu extends Menu implements EventHandler<ActionEvent> {
	
	private final ChartingView chartingView;
	
	public SaveAsChartMenu(final ChartingView chartingView) {
		super(MessageSource.get("Chart"));
		this.chartingView = chartingView;	
		OChartGroup.ALL.addListener(new ListChangeListener<OChartGroup>(){
			@Override
			public void onChanged(ListChangeListener.Change<? extends OChartGroup> change) {
				while(change.next()){
					if(change.wasAdded()){
						addItems(change.getAddedSubList());
					}else if(change.wasRemoved()){
						List<MenuItem> removableItems = new ArrayList<MenuItem>();
						for(OChartGroup chartGroup : change.getRemoved()){
							for(MenuItem item : getItems()){
								if(chartGroup.equals(item.getUserData())){
									removableItems.add(item);
								}
							}
						}
						getItems().removeAll(removableItems);
					}
				}
			}
		});
		addItems(OChartGroup.ALL);
		OChartGroup.loadAll();
	}
	
	private void addItems(List<? extends OChartGroup> chartGroups){
		for(OChartGroup chartGroup : chartGroups){
			MenuItem item = new MenuItem();
			item.textProperty().bindBidirectional(chartGroup.nameProperty());
			item.setUserData(chartGroup);
			item.setOnAction(SaveAsChartMenu.this);
			getItems().add(item);
		}
	}
	
	@Override
	public void handle(ActionEvent event) {
		MenuItem item = (MenuItem)event.getSource();
		OChartGroup chartGroup = (OChartGroup)item.getUserData();
		
		ChartingViewDTO dto = new ChartingViewDTO(chartingView);
		SavedChart savedChart = new SavedChart();
		Scrip scrip = chartingView.getPrimaryChart().getPrimaryPlot().getExtraValue();
		savedChart.setChartGroupId(chartGroup.getId());
		savedChart.setName(scrip.getName());
		savedChart.setPrimaryScripId(scrip.getId());
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		XMLEncoder xmlEncoder = new XMLEncoder(baos);
		xmlEncoder.writeObject(dto);
		xmlEncoder.close();
		savedChart.setContent(baos.toString());
		
		Client.CHARTING_CLIENT.save(savedChart);
		chartGroup.getCharts().add(savedChart);
	}

}
